﻿using PosClient.Interfaces;
using PosClient.Model;
using PosClient.ViewModel;
using ReactiveUI;
using Splat;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive;
using System.Text;
using System.Threading.Tasks;

namespace PosClient.ViewModel
{
    public class PresentViewModel: ReactiveObject
    {
        private int _Count;
        public int Count
        {
            get => _Count;
            set => this.RaiseAndSetIfChanged(ref _Count, value);
        }

        private string _PluName;
        public string PluName
        {
            get => _PluName;
            set => this.RaiseAndSetIfChanged(ref _PluName, value);
        }

        private string _PluCode;
        public string PluCode
        {
            get => _PluCode;
            set => this.RaiseAndSetIfChanged(ref _PluCode, value);
        }

        private Plu _Plu;
        public Plu Plu
        {
            get => _Plu;
            set => this.RaiseAndSetIfChanged(ref _Plu, value);
        }

        public MainViewModel ParentViewModel { get; private set; }

        public ReactiveCommand<Unit, Result<Plu>> GetGoodCommand { get; }

        public PresentViewModel()
        {
            var canCode = this.WhenAnyValue(vm => vm.PluCode, (x) => !string.IsNullOrEmpty(x));

            ParentViewModel = Locator.Current.GetService<MainViewModel>();

            GetGoodCommand = ReactiveCommand.Create(GetGoodCommandImpl, canCode);
        }

        private Result<Plu> GetGoodCommandImpl()
        {
            Result<Plu> result = new Result<Plu>()
            { 
                Success = true,
                Message = "请求成功"
            };
            var server = Locator.Current.GetService<IPluService>();
            server.SearchPlu(PluCode,out Plu plu);
            if (plu != null)
            {
                plu.Tag = Plu.PluTag.Present;
                plu.Amount = 0;
                plu.OriginPrice = plu.Price;
                plu.Price = 0;
                plu.PluName += "（赠送）";
                result.Data = plu;
            }
            else
            {
                result.Success = false;
                result.Message = $"查询失败{PluCode}";
            }
            return result;
        }

    }
}
